/* 
目的:
将host内存 data拷贝到 device内存
float data[16] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.0, 11.1, 12.2, 13.3, 14.4, 15.5, 16.6};
*/

#include <iostream>
#include <cuda_runtime.h>
using namespace std;

// cuda核函数: 计算数组的立方和
__global__ void cal_array_cube(float *data, int size, float *result)
{
    float sum = 0.0;
    for (int i = 0; i < size; i++){
        sum += data[i] * data[i] * data[i];
    }

    *result = sum;
}

int main()
{
    // 1. 定义host内存
    float data[16] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.0, 11.1, 12.2, 13.3, 14.4, 15.5, 16.6};
    float result = 0.0;

    // 2. 定义device内存, 并将host内存拷贝到device内存
    float *d_data, *d_result;
    cudaMalloc((void **)&d_data, sizeof(data));
    cudaMemcpy(d_data, data, sizeof(data), cudaMemcpyHostToDevice);
    cudaMalloc((void **)&d_result, sizeof(float));

    // 3. 调用核函数
    cal_array_cube<<<1,1>>>(d_data, 16, d_result);

    // 4. 将device内存拷贝到host内存
    cudaMemcpy(&result, d_result, sizeof(float), cudaMemcpyDeviceToHost);

    // 5. 打印结果
    cout << "gpu result = " << result << endl;

    // cpu计算结果
    float cpu_result = 0.0;
    for (int i = 0; i < 16; i++){
        cpu_result += data[i] * data[i] * data[i];
    }
    cout << "cpu result = " << cpu_result << endl;

    // 6. 释放device内存
    cudaFree(d_data);
    cudaFree(d_result);

    return 0;
}